package com.tiancheng.trade.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiancheng.trade.order.enums.SystemSourceEnum;
import com.tiancheng.trade.order.mapper.SubOrderStatusMapper;
import com.tiancheng.trade.order.model.SubOrderStatus;
import com.tiancheng.trade.order.service.SubOrderStatusService;
import com.tiancheng.trade.order.util.cache.OrderCache;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 子订单状态映射service接口实现
 *
 * @author kellen
 * @date 2024/5/1
 */
@Slf4j
@Service
public class SubOrderStatusServiceImpl implements SubOrderStatusService {

    @Resource
    private SubOrderStatusMapper subOrderStatusMapper;

    @Override
//    @Cacheable(value = "sub_order_biz_status", key = "#p0")
    public Map<String, String> find(String orderSource, String bizStatus) {
        String cacheKey = this.getCacheKey(orderSource, bizStatus);
        Optional<Map<String, String>> subOrderStatusBiz = OrderCache.getSubOrderStatusBiz(cacheKey);
        if (subOrderStatusBiz.isPresent()) {
            //log.info("获取到缓存业务状态信息，key:{},map:{}",cacheKey,subOrderStatusBiz.get());
            return subOrderStatusBiz.get();
        }
        QueryWrapper<SubOrderStatus> conditions = new QueryWrapper<>();
        conditions.eq("order_source", orderSource);
        conditions.eq("biz_status", bizStatus);
        List<SubOrderStatus> subOrderStatusList = subOrderStatusMapper.selectList(conditions);
        Map<String, String> statusMap = subOrderStatusList.stream().collect(
                Collectors.toMap(SubOrderStatus::getBizStatus, x -> x.getSubOrderStatus() + ":" + x.getVerification()));
        if (statusMap != null && statusMap.size() > 0) {
            log.info("设置缓存业务状态信息，key:{},map:{}", cacheKey, statusMap);
            OrderCache.setSubOrderStatusBiz(cacheKey, statusMap);
        }
        return statusMap;
    }

    private String getCacheKey(String orderSource, String bizStatus) {
        String key = orderSource;
        if (StringUtils.isNotEmpty(bizStatus)) {
            key += bizStatus;
        }
        return key;
    }
}
